<template>
  <div class="container">
    <br />
    <h1>我的音乐列表</h1>
    <div class="music_list">
      <ul>
        <li
          v-for="(item, index) in musicList"
          :key="index"
          @click="playMusic(item.src,index)"
        >
          {{ item.musicName }}
        <span v-show="flag===index" class="duration">{{durationMusic}}</span>
        <div class="mask"  :style="{width: flag===index?maskWidth:''}"></div>
        </li>
      </ul>
    </div>
    <!-- 音乐播放 -->
    <audio
      controls="controls"
      @canplay="getDuration"
      @timeupdate="updateTime"
      ref="audio"
      loop
    >
      <source :src="musicUrl" type="audio/mpeg" />
    </audio>
  </div>
</template>

<script>
import { musicList } from "./meta/data.js"
export default {
  name: "PlayAudio",
  data() {
    return {
      musicList: musicList,
      musicUrl: "",
      currentTime: "",
      duration: "",
      flag:'',
      durationMusic:""+'',
    };
  },
  computed: {
    maskWidth() {
      return (this.currentTime / this.duration)*100 +'%'
    },
  },
  methods: {
    getDuration() {
      console.log(this.$refs.audio.duration); //此时可以获取到duration
      this.duration = this.$refs.audio.duration;
    },
    updateTime(e) {
      this.currentTime = e.target.currentTime; //获取audio当前播放时间
      this.durationMusic = Math.floor(this.duration-e.target.currentTime) +"''"
    },
    playMusic(musicUrl,index) {
      setTimeout(()=> {
        this.flag = index
      },500)
      // 赋值url地址
      this.musicUrl = musicUrl;
      // 获取audio的dom
      let audio = this.$refs.audio;
      // 第一次播放是url地址为空--必须要重置--load()
      if (audio.currentSrc === "") {
        audio.load();
        audio.play();
        return;
      }
      // 判断当前的url与点击的url是否一致
      if (audio.currentSrc === musicUrl) {
        audio.paused ? audio.play() : audio.pause();
        return;
      } else {
        audio.load();
        audio.play();
        return;
      }
    },
  },
  watch: {
    currentSong() {
      //监听正在播放的歌曲改变
      this.$nextTick(() => {
        this.$refs.audio.play();
        console.log(this.$refs.audio.duration); //此时duration为NaN
      });
    },
  },
};
</script>

<style>
.music_list li {
  position: relative;
  width: 200px;
  height: 30px;
  line-height: 30px;
  background-color: #ccc;
  list-style-type: none;
  margin: 5px auto;
  padding: 0 0 0 25px;
  border-radius: 5px;
  cursor: pointer;
  overflow: hidden;
  text-align: left;
  box-sizing: border-box;
}
.music_list li .mask {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 0;
  opacity: 0.7;
  background-color: #67d67a;
}
.music_list li .duration {
  position: absolute;
  top: 0;
  right: 20px;
}
</style>